package register

import (
	"time"

	"gitee.com/fanshuaiself/wss-gateway/pkg/nacos"
)

type RegisterPlugin struct {
	intervalSeconds int 
	HealthChecker HealthChecker
	closeCh chan struct{}

	health bool
}

func NewRegisterPlugin() *RegisterPlugin {
	return &RegisterPlugin{
		intervalSeconds: 30,
		HealthChecker: &httpHealthChecker{},
		closeCh: make(chan struct{}, 1),
	}
}

func (r *RegisterPlugin) Start(globalCh chan struct{}) error {
	go r.doStart()
	return nil 
}

func (r *RegisterPlugin) doStart() {
	running := true
	for running {
		select {
		case <- r.closeCh:
			running = false
		case <- time.After(time.Duration(r.intervalSeconds) * time.Second):
			r.checkAndRegister()
		}
	}
	nacos.DeRegister()
}

func (r *RegisterPlugin) checkAndRegister() {
	up := r.HealthChecker.health()
	if r.health == up {
		return 
	}

	r.health = up 
	if up {
		nacos.Register(up)
	} else {
		nacos.DeRegister()
	}
}

func (r *RegisterPlugin) Stop() {
	r.closeCh <- struct{}{}
}